const Koa= require("koa");
const router = require("koa-router")();
const app = new Koa();
const Top250Model = require("./models/top250");
const cors = require("koa2-cors");
const bodyParser = require("koa-bodyparser");

const koaBody = require('koa-body')     //
const static = require('koa-static');   //
const fs = require("fs");
const path = require("path");
app.use(static(`${process.cwd()}/static`));
app.use(koaBody({
    // 支持文件格式
    multipart: true,
    formidable: {
        maxFileSize: 200*1024*1024,
        // 保留文件扩展名
    keepExtensions: true
    }
}));
router.post("/doAdd",async ctx=>{
    var {title,slogo,evaluate,rating,labels,collected} = ctx.request.body;
    // console.log(ctx.request.body)
    const file = ctx.request.files.file
    // console.log(file)
    const basename = path.basename(file.path)
    /* 1.将本地图片存到服务器 */
    // 创建可读流
    const reader = fs.createReadStream(file.path);
    // 获取上传文件扩展名
    let filePath = process.cwd() + `/static/${basename}`;
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);
    
    /* 2.将服务器上的图片地址存入数据库 */
    // console.log(ctx.origin)                 //http:localhost:8080
    var  pic = `${ctx.origin}/${basename}`
    // console.log(pic)
    var data = new Top250Model({
        title,
        pic,
        slogo,
        evaluate,
        rating,
        labels,
        collected:Boolean(collected)
    })
    data.save(err => {
        if (err) {
            throw err
        };
    })
})